<template>
    <div class="main">
        <section>
            <div class="btn-block flex-box">
              <div>
                <el-button v-if="rightsButtons['add']" type="success" size="small" icon="el-icon-circle-plus" plain @click="showAdd">新建箱起活动</el-button>
              </div>
            </div>
            <el-form ref="searchForm" class="search-block" :model="listQuery" label-position="right" label-width="120px">
                <el-row :gutter="50">
                    <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                        <el-form-item label="活动名称：" prop="seriesName">
                            <el-input @keyup.enter.native="search" v-model="listQuery.seriesName" placeholder="活动名称" maxlength="50" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="16" :md="12" :lg="8" :xl="6">
                        <el-form-item label="活动状态：" prop="upshelf">
                            <el-select v-model="listQuery.upshelf" clearable>
                                <el-option  label="已上架" :value="1"></el-option>
                                <el-option  label="已下架" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="" class="btn-item">
                    <el-button type="primary" size="mini" icon="el-icon-search" plain @click="search">搜索</el-button>
                    <span class="btn-reset" @click="resetForm('searchForm')">清空搜索条件</span>
                </el-form-item>
            </el-form>
            <div class="btn-block" v-if="rightsButtons['export']">
              <el-button type="primary" :loading="exportLoading" @click="exportExcel">导出</el-button>
            </div>
            <el-table :data="list" v-loading="listLoading" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
                <el-table-column align="center" type="index" label="序号" width="80">
                </el-table-column>
                <el-table-column align="center" label="活动系列名称" prop="seriesName"></el-table-column>
                <el-table-column align="center" label="活动商品" prop="seriesGoodsName" show-overflow-tooltip width="280"></el-table-column>
                <el-table-column align="center" label="活动状态" prop="upshelf" width="160">
                    <template slot-scope="scope">
                        <span v-if="scope.row.upshelf===1" style="color: green">已上架</span>
                        <span v-if="scope.row.upshelf===0" style="color: #9b9b9b">已下架</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="是否展示" prop="isShow" width="160">
                    <template slot-scope="scope">
                        <span v-if="scope.row.isShow" style="color: green">是</span>
                        <span v-else style="color: #9b9b9b">否</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="创建时间">
                    <template slot-scope="scope">
                        <span>{{ formatDate(scope.row.createdAt, 'YYYY-MM-DD HH:mm:ss') }}</span>
                    </template> 
                </el-table-column>
                <el-table-column align="center" label="操作" width="300" v-if="rightsButtons['edit'] || rightsButtons['goodsList'] || rightsButtons['fail']">
                    <template slot-scope="scope">
                        <el-button v-if="rightsButtons['edit']" type="primary" size="mini" @click="showEdit(scope.row)">编辑</el-button>
                        <router-link v-if="rightsButtons['goodsList']" :to="{name: 'boxTransActivityGoodsList', params: {id: scope.row.seriesId}, query: { upshelf: scope.row.upshelf }}">
                            <el-button type="primary" plain size="mini">商品管理</el-button>
                        </router-link>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="listQuery.pageIndex"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="listQuery.pageSize"
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="listTotal">
            </el-pagination>
            <el-dialog :title="formData.id ? '编辑箱起活动' : '新建箱起活动'" :visible.sync="dialogFormVisible">
                <el-form :model="formData" :rules="formRules" size="medium" ref="form" label-width="120px">
                    <el-form-item label="活动系列名称:" prop="seriesName">
                        <el-input v-model="formData.seriesName" :disabled="formData.upshelf===-1"></el-input>
                    </el-form-item>
                    <el-form-item label="是否上架:" prop="upshelf">
                        <el-switch
                                v-model="formData.upshelf"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="1"
                                :inactive-value="0"
                                :disabled="!formData.id || formData.upshelfNum===0 || formData.upshelf===-1"
                                @change="changeIsSell">
                        </el-switch><span v-show="formData.id && formData.upshelfNum===0" class="goods-tips">商品未上架</span>
                    </el-form-item>
                    <el-form-item label="是否展示:" prop="isShow">
                        <el-switch
                                v-model="formData.isShow"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="1"
                                :inactive-value="0"
                                :disabled="!formData.upshelf || formData.upshelf===-1">
                        </el-switch>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="save" :loading="btnLoading" :disabled="btnLoading">保存</el-button>
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                </div>
            </el-dialog>
        </section>
    </div>
</template>
<script>
    import { debounce } from  '../../../utils/index';
    import { regexp } from '@/utils/tools'
    import moment from 'moment'
    export default {
        name: 'activityNewBox',
        data(){
            return {
              exportLoading: false,
                activityChannel: {
                  '0': '零售',
                  '1': '礼包',
                  '2': '零售+礼包',
                  '3': '云仓'
                },
                tags: {
                  "0" : "无",
                  "1" : "ZHO专属"
                },
                listQuery: {
                    pageIndex: 1,
                    pageSize: 10,
                    seriesName: '',
                    seriesType: 4,
                    upshelf: ''
                },
                listLoading: false,
                list: [],
                listTotal: 0,
                bonusConfig: [],
                dialogFormVisible: false,
                btnLoading: false,
                formData: {
                    seriesName: '',
                    seriesType: 4,
                    img: '',
                    sort: 1,
                    labelId: 0,
                    upshelf: 0,
                    isSell: 0,
                    isShow: 1
                },
                formRules: {
                    seriesName: [{required: true, message: '不能为空', trigger: 'change'}],
                    img: [{required: true, message: '请上传活动图片'}],
                    sort: [{ pattern: regexp.positiveInt, message: '必须为正整数', trigger: 'change' }]
                }
            }
        },
        activated(){
            this.getBonusConfig()
            this.getList()
        },
        created(){
            this.getList()
          if (this.$store.getters.cachedViews.length === 0) {
            this.getBonusConfig()
            
          }
        },
        methods: {
          handleFail (row) {
            this.$confirm(`失效后活动将永久作废，是否确认失效?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.request({
                url: '/bsnl-product/box/updateFailure',
                method: 'get',
                params: {
                  boxSeriesId: row.seriesId
                }
              }).then((res) => {
                if (res.status === 200) {
                  this.$message.success(res.message)
                  this.getList()
                }
              }).catch(err => {
                console.log(err)
              })
            }).catch(err => {
              console.log(err)
            })
          },
          // 导出搜索结果
          exportExcel() {
            this.exportLoading = true
            this.request({
              url: "/bsnl-product/box/exportExcel",
              method: "post",
              data: this.listQuery,
              responseType: 'blob'
            }).then(res => {
              let date = moment().format('YYYYMMDD/HHmmss').replace(/\//g, '_')
              let filename = `箱起${date}.xls`
              this.downloadFile(res, filename)
              this.exportLoading = false
            }).catch(err => {
              console.log(err)
              this.exportLoading = false
            })
          },
            search() {
                this.listQuery.pageIndex =1
                this.getList()
            },
            // 清空搜索条件
            resetForm (formName) {
                this.$nextTick(() => {
                    this.$refs[formName].resetFields()
                })
            },
            getBonusConfig() {
                this.request({
                    url: '/bsnl-product/box/bonus/config/list',
                    method: 'post',
                    data: {pageIndex: 1, pageSize: 99999}
                }).then((res) => {
                    this.bonusConfig = res.data
                }).catch(err => {
                   console.log(err)
                })
            },
            getList(){
                this.listLoading = true;
                this.request({
                    url: '/bsnl-product/box/list',
                    method: 'post',
                    data: this.listQuery
                }).then(({data, total}) => {
                    this.list = data;
                    this.listTotal = total;
                    this.listLoading = false;
                }).catch(err => {
                    console.log(err);
                    this.list = [];
                    this.listTotal = 0;
                    this.listLoading = false;
                });
            },
            handleSizeChange (value) {
                this.listQuery.pageSize = value
                this.getList()
            },
            handleCurrentChange(val){
                this.listQuery.pageIndex = val;
                this.getList();
            },
            showAdd(){
                this.formData = {
                    seriesName: '',
                    img: '',
                    labelId: 0,
                    upshelf: 0,
                    isSell: 0,
                    isShow: 0,
                    sort: 1
                };
                this.dialogFormVisible = true;
                this.btnLoading = false;
                this.$nextTick(()=>{
                    this.$refs.form.clearValidate()
                });
            },
            showEdit(row){
                this.formData = Object.assign({}, row);
                this.dialogFormVisible = true;
                this.btnLoading = false;
                this.$nextTick(()=>{
                    this.$refs.form.clearValidate()
                });
            },
            uploadSuccess(res) {
                this.formData.img = this.replaceImgUrl(res.filePath);
            },
            changeIsSell(){
                this.formData.isSell = this.formData.upshelf && this.formData.isSell;
            },
            save: debounce(function () {
                this.$refs.form.validate(valid => {
                    if (!valid || this.btnLoading) {
                        return false;
                    }

                    this.btnLoading = true;
                    this.request({
                        url: '/bsnl-product/box/priviPack/doSave',
                        method: 'post',
                        data: this.formData
                    }).then(() => {
                        this.btnLoading = false;
                        this.dialogFormVisible = false;
                        this.$message.success('保存成功');
                        this.getList();
                    }).catch(err => {
                        this.btnLoading = false;
                    });
                });
            }, 1500, true)
        }
    }
</script>
<style lang="scss">
    @import "../../../styles/mixin";
    .banner-container{
        .avatar-uploader .el-upload{
            width: 120px;
            height: 120px;
            line-height: 118px;
        }
    }
    .flex-box {
      display: flex;
      justify-content: space-between;
    }
    .goods-tips {
      color: red;
      margin-left: 20px;
    }
    .activity-img{
        @include flex;
        @include center;
        min-height: 60px;
        img{
            width:100%;
            height: 100%;
            max-width: 60px;
            max-height: 60px;
        }
    }
    .el-row{
        margin-bottom: 12px;
    }
</style>
